<template>
  <div class="outbound">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="出库单号">
          <el-input v-model="searchForm.outboundNo" placeholder="请输入出库单号" clearable />
        </el-form-item>
        <el-form-item label="出库类型">
          <el-select v-model="searchForm.outboundType" placeholder="请选择出库类型" clearable>
            <el-option label="销售出库" value="sales" />
            <el-option label="生产领料" value="production" />
            <el-option label="调拨出库" value="transfer" />
            <el-option label="其他出库" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="已出库" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="handleAdd" v-if="hasPermission('warehouse:outbound:add')">
        <el-icon><Plus /></el-icon>新增出库单
      </el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="card">
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="outboundNo" label="出库单号" width="150" />
        <el-table-column prop="outboundType" label="出库类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getOutboundTypeType(row.outboundType)">
              {{ getOutboundTypeText(row.outboundType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sourceNo" label="来源单号" width="150" />
        <el-table-column prop="warehouseName" label="出库仓库" width="120" />
        <el-table-column prop="totalQuantity" label="总数量" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="outboundTime" label="出库时间" width="180" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEdit(row)"
              v-if="hasPermission('warehouse:outbound:edit') && row.status === 'pending'"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleConfirm(row)"
              v-if="hasPermission('warehouse:outbound:edit') && row.status === 'approved'"
            >
              确认出库
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              v-if="hasPermission('warehouse:outbound:delete') && row.status === 'pending'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库类型" prop="outboundType">
              <el-select v-model="form.outboundType" placeholder="请选择出库类型" style="width: 100%">
                <el-option label="销售出库" value="sales" />
                <el-option label="生产领料" value="production" />
                <el-option label="调拨出库" value="transfer" />
                <el-option label="其他出库" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" style="width: 100%">
                <el-option
                  v-for="warehouse in warehouses"
                  :key="warehouse.id"
                  :label="warehouse.name"
                  :value="warehouse.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="来源单号" prop="sourceNo">
              <el-input v-model="form.sourceNo" placeholder="请输入来源单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库日期" prop="outboundDate">
              <el-date-picker
                v-model="form.outboundDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <!-- 出库明细 -->
        <el-form-item label="出库明细">
          <div class="outbound-items">
            <div
              v-for="(item, index) in form.items"
              :key="index"
              class="outbound-item"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item :label="'物料' + (index + 1)" :prop="`items.${index}.materialId`">
                    <el-select v-model="item.materialId" placeholder="选择物料" style="width: 100%">
                      <el-option
                        v-for="material in materials"
                        :key="material.id"
                        :label="material.name"
                        :value="material.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="数量" :prop="`items.${index}.quantity`">
                    <el-input-number v-model="item.quantity" :min="1" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="单价" :prop="`items.${index}.price`">
                    <el-input-number v-model="item.price" :min="0" :precision="2" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" @click="removeItem(index)" :disabled="form.items.length === 1">
                    删除
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" @click="addItem">添加物料</el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 搜索表单
const searchForm = reactive({
  outboundNo: '',
  outboundType: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 仓库数据
const warehouses = ref([
  { id: 1, name: '主仓库' },
  { id: 2, name: '原料仓库' },
  { id: 3, name: '成品仓库' }
])

// 物料数据
const materials = ref([
  { id: 1, name: '原材料A', code: 'M001' },
  { id: 2, name: '原材料B', code: 'M002' },
  { id: 3, name: '成品C', code: 'M003' }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  outboundType: '',
  warehouseId: '',
  sourceNo: '',
  outboundDate: '',
  remark: '',
  items: [{ materialId: '', quantity: 1, price: 0 }]
})

// 表单验证规则
const formRules = {
  outboundType: [{ required: true, message: '请选择出库类型', trigger: 'change' }],
  warehouseId: [{ required: true, message: '请选择出库仓库', trigger: 'change' }],
  sourceNo: [{ required: true, message: '请输入来源单号', trigger: 'blur' }],
  outboundDate: [{ required: true, message: '请选择出库日期', trigger: 'change' }],
  'items.0.materialId': [{ required: true, message: '请选择物料', trigger: 'change' }],
  'items.0.quantity': [{ required: true, message: '请输入数量', trigger: 'blur' }],
  'items.0.price': [{ required: true, message: '请输入单价', trigger: 'blur' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    outboundNo: 'OUT-2024-001',
    outboundType: 'sales',
    sourceNo: 'SO-2024-001',
    warehouseName: '成品仓库',
    totalQuantity: 50,
    totalAmount: 7500.00,
    status: 'completed',
    createTime: '2024-01-15 10:30:00',
    outboundTime: '2024-01-15 14:20:00',
    remark: '销售出库'
  },
  {
    id: 2,
    outboundNo: 'OUT-2024-002',
    outboundType: 'production',
    sourceNo: 'WO-2024-001',
    warehouseName: '原料仓库',
    totalQuantity: 100,
    totalAmount: 1500.00,
    status: 'approved',
    createTime: '2024-01-14 14:20:00',
    outboundTime: '',
    remark: '生产领料'
  },
  {
    id: 3,
    outboundNo: 'OUT-2024-003',
    outboundType: 'transfer',
    sourceNo: 'TR-2024-001',
    warehouseName: '主仓库',
    totalQuantity: 30,
    totalAmount: 4500.00,
    status: 'pending',
    createTime: '2024-01-13 09:15:00',
    outboundTime: '',
    remark: '调拨出库'
  }
]

// 获取出库类型样式
const getOutboundTypeType = (type) => {
  const typeMap = {
    sales: 'success',
    production: 'primary',
    transfer: 'warning',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取出库类型文本
const getOutboundTypeText = (type) => {
  const textMap = {
    sales: '销售出库',
    production: '生产领料',
    transfer: '调拨出库',
    other: '其他出库'
  }
  return textMap[type] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已审核',
    completed: '已出库',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    outboundNo: '',
    outboundType: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 加载数据
const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增出库单'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑出库单'
  Object.assign(form, {
    id: row.id,
    outboundType: row.outboundType,
    warehouseId: 1, // 模拟数据
    sourceNo: row.sourceNo,
    outboundDate: row.outboundTime ? row.outboundTime.split(' ')[0] : '',
    remark: row.remark,
    items: [{ materialId: 1, quantity: 1, price: 100 }]
  })
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看功能开发中...')
}

// 确认出库
const handleConfirm = async (row) => {
  try {
    await ElMessageBox.confirm('确定要确认出库吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟确认出库
    ElMessage.success('出库确认成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个出库单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟删除
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 添加物料项
const addItem = () => {
  form.items.push({ materialId: '', quantity: 1, price: 0 })
}

// 删除物料项
const removeItem = (index) => {
  form.items.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟提交
    setTimeout(() => {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
      submitLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    outboundType: '',
    warehouseId: '',
    sourceNo: '',
    outboundDate: '',
    remark: '',
    items: [{ materialId: '', quantity: 1, price: 0 }]
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.outbound {
  .outbound-items {
    .outbound-item {
      border: 1px solid $border-color-light;
      border-radius: 4px;
      padding: 15px;
      margin-bottom: 15px;
    }
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 